import axios from 'axios'
import baseUrl from './setBaseUrl'
import { getCookie } from './cookieUtils'

// axios配置
axios.defaults.timeout = 5000
axios.defaults.baseURL = baseUrl

// http request 拦截器
axios.interceptors.request.use(
   config => {
      const token = getCookie('token')
      config.data = JSON.stringify(config.data)
      config.headers = {
         'Content-Type': 'application/json; charset=utf-8'
      }
      if (token) {
         config.headers['Authorization'] = token
      }

      return config
   },
   err => {
      return Promise.reject(err)
   }
)

// http response 拦截器
axios.interceptors.response.use(
   response => {
      const res = response.data
      if (res.code >= 200 && res.code < 300) {
         return res
      } else {
         return Promise.reject(res)
      }
   },
   err => {
      return Promise.reject(err.response.data.msg || '请求出错')
   }
)

/**
 * get 请求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function get(url, params = {}) {
   return new Promise((resolve, reject) => {
      axios.get(url, {
         params: params
      }).then(response => {
         resolve(response.data)
      }).catch(err => {
         reject(err)
      })
   })
}

/**
 * post 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
   return new Promise((resolve, reject) => {
      axios.post(url, data).then(res => {
         resolve(res.data)
      }).catch(err => {
         reject(err)
      })
   })
}
